import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:freedom/const/app_content.dart';
import 'package:freedom/const/game_const.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/page/mahjong/common/message_content.dart';
import 'package:freedom/page/mahjong/mahjong_game.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/util/customer_dialog.dart';
import 'package:freedom/util/http.dart';
import 'package:freedom/widget/i_text_filed.dart';

typedef _CallBack = void Function(String roomCode);

class GameMessage extends StatefulWidget {
  final MahjongIndexGame game;
  GameMessage({required MahjongIndexGame this.game});

  @override
  _GameMessageState createState() => _GameMessageState();
}

class _GameMessageState extends State<GameMessage>
    with SingleTickerProviderStateMixin {
  TabController? _tabController;
  List<Widget>? _childList;
  Widget? _child;
  TextFiledValidata? _textFiled;

  MahjongIndexGame get game => widget.game;

  @override
  void dispose() {
    super.dispose();
    _tabController!.dispose();
  }

  @override
  void initState() {
    super.initState();
    _textFiled = TextFiledValidata();
    _tabController = new TabController(length: 2, vsync: this);
    _child = buildSendMessage();
    _childList = [buildSendMessage(), buildEmoji()];
    _tabController!.addListener(() {
      _child = _childList![_tabController!.index];
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        GestureDetector(
          onTap: () {
            game.overlays.remove(SystemOverlay.messageInfoDialog);
          },
          child: Container(
            color: Colors.transparent,
            width: double.infinity,
            height: double.infinity,
          ),
        ),
        Center(
            child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(5.r),
            boxShadow: [
              BoxShadow(
                color: const Color.fromARGB(255, 19, 18, 18).withOpacity(0.5),
                spreadRadius: 5.r,
                blurRadius: 7.r,
                offset: const Offset(0, 3), // changes position of shadow
              ),
            ],
          ),
          width: 500.w,
          height: 200.h,
          child: ClipRRect(
            borderRadius: BorderRadius.circular(5.r),
            child: Material(
                child: Column(
              children: [
                SizedBox(
                  height: 30.h,
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      Container(
                        color: Colors.white,
                        child: TabBar(
                          controller: _tabController,
                          tabs: [
                            Container(
                                height: 30.h,
                                padding: EdgeInsets.only(left: 5.h),
                                margin: EdgeInsets.only(bottom: 5.h),
                                width: double.infinity,
                                alignment: Alignment.centerLeft,
                                child: Center(
                                  child: Text(
                                    "消息",
                                    style: TextStyle(
                                        color: Colors.black, fontSize: 18.sp),
                                  ),
                                )),
                            Container(
                                height: 30.h,
                                padding: EdgeInsets.only(left: 2.h),
                                margin: EdgeInsets.only(bottom: 2.h),
                                alignment: Alignment.centerLeft,
                                child: Center(
                                    child: Text(
                                  "表情",
                                  style: TextStyle(
                                      color: Colors.black, fontSize: 18.sp),
                                )))
                          ],
                        ),
                      ),
                      Align(
                        alignment: const Alignment(1, -1),
                        child: InkWell(
                          child: Container(
                            /*  decoration: BoxDecoration(
                            border:
                                Border.all(color: Colors.black, width: 1.0)), */
                            child: Icon(
                              Icons.close,
                              size: 20.h,
                              weight: 900,
                              color: Colors.grey,
                            ),
                          ),
                          onTap: () {
                            game.overlays
                                .remove(SystemOverlay.messageInfoDialog);
                          },
                        ),
                      )
                    ],
                  ),
                ),
                Expanded(child: _child!)
              ],
            )),
          ),
        ))
      ],
    ); /* GestureDetector(
      onTap: () {
        game.overlays.remove(SystemOverlay.messageInfoDialog);
      },
      child: Container(
        color: Colors.transparent,
        width: double.infinity,
        height: double.infinity,
        child: ,
      ),
    ); */
  }

  Container buildEmoji() {
    return Container(
      color: Colors.white,
      child: GridView(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5, // 列数
          mainAxisSpacing: 0.0, // 垂直间距
          crossAxisSpacing: 0.0, // 水平间距
        ),
        children: GameConst.emojiList
            .map((item) => InkWell(
                  onTap: () {
                    sendMessage(MessageTypeConst.emoji, item.code, 0);
                  },
                  child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    height: 40.h,
                    width: 40.h,
                    placeholder: (context, url) =>
                        const CircularProgressIndicator(),
                    errorWidget: (context, url, error) =>
                        const Icon(Icons.error),
                    imageUrl: item.networkImageStc,
                  ),
                ))
            .toList(),
      ),
    );
  }

  Column buildSendMessage() {
    return Column(
      children: [
        Expanded(
            child: SingleChildScrollView(
          child: Container(
              color: Colors.white,
              padding: EdgeInsets.all(5.h),
              child: Column(
                children: soundMessageArray
                    .asMap()
                    .keys
                    .map((index) => InkWell(
                        onTap: () {
                          sendMessage(MessageTypeConst.chart,
                              soundMessageArray[index], index);
                        },
                        child: messageItem(soundMessageArray[index])))
                    .toList(),
              )),
        )),
        SizedBox(
          height: 5.h,
        ),
        Container(
          height: 20.h,
          alignment: Alignment.topCenter,
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(5.r)),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ITextFiled(
                500.w - 60.h,
                20.h,
                inputDecoration: const BoxDecoration(color: Colors.white),
                hintText: "请输入需要发送的消息",
                defaultStr: "",
                showError: false,
                obscureText: false,
                textFiledValidata: _textFiled,
                preIcon: Icons.message_outlined,
              ),
              Container(
                width: 60.h,
                height: 20.h,
                decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 153, 197, 233),
                    borderRadius: BorderRadius.all(Radius.circular(5.h))),
                child: InkWell(
                    onTap: () {
                      if (_textFiled!.value == null ||
                          _textFiled!.value!.isEmpty) {
                        CustomerDialog.showText("请输入消息");
                      } else {
                        sendMessage(
                            MessageTypeConst.chart, _textFiled!.value, null);
                      }
                    },
                    child: Center(
                      child: Text(
                        "发送",
                        style: TextStyle(
                            fontSize: 10.h, height: 1.0, color: Colors.white),
                      ),
                    )),
              )
            ],
          ),
        )
      ],
    );
  }

  void sendMessage(int type, String? text, int? index) {
    if (text == null) {
      return;
    }
    var data = MessageContent<ChatMessage>(
            type: MessageType.CHART,
            messageFromUid: MessageType.CHART,
            body: ChatMessage(text: text, type: type, index: index))
        .toJson();
    Http.getInstance().request<Restful>(ApiRouter.roomMessage,
        contentType: ContentType.json,
        type: RequestEnum.POST,
        data: data, success: (data) {
      game.overlays.remove(SystemOverlay.messageInfoDialog);
    });
  }

  Widget messageItem(str) {
    return Container(
        height: 30.h,
        padding: EdgeInsets.only(left: 5.h),
        margin: EdgeInsets.only(bottom: 5.h),
        width: double.infinity,
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
            color: Colors.grey[200], borderRadius: BorderRadius.circular(5.h)),
        child: Text(
          str,
          style: TextStyle(fontSize: 12.h),
        ));
  }
}
